#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

#include <sys/wait.h>



int main(void)

{

    int count = 1;

    pid_t childpid, terminatedid;

    

    childpid = fork(); /* child duplicates parent’s address space */

    if (childpid < 0) {

        perror("fork()");

        return EXIT_FAILURE;

    }

    else

        if (childpid == 0) { /* This is child pro */
        //子进程空间

            count++;

            printf("child pro pid = %d, count = %d (addr = %p)\n", getpid(), count, &count); 

            printf("child sleeping ...\n");

            sleep(5); /* parent wait() during this period */

            printf("\nchild waking up!\n");

        }

        else { /* This is parent pro */
        //父进程空间

            //加了wait之后,一定是子进程先结束,然后操作系统检查所有子进程的状态,最后才回收子进程的PID
            //结果是terminatedid = 子进程的pid;
            terminatedid = wait(0);

            printf("Parent pro pid = %d, tersminated pid = %d, count = %d (addr = %p)\n", getpid(), terminatedid, count, &count);

        }

        //子进程先打印出来

    printf("\nTesting point by %d\n", getpid()); /* executed first by child and then parent */

    return EXIT_SUCCESS;

}

